<script setup>
import TodoHeader from './components/TodoHeader.vue';
import TodoMain from './components/TodoMain.vue';
import TodoFooter from './components/TodoFooter.vue';
import { ref, watch } from 'vue';

const list = ref(
  JSON.parse(localStorage.getItem('todos')) || [
    { id: 1, name: '吃饭', done: true },
    { id: 2, name: '睡觉', done: true },
    { id: 3, name: '敲代码', done: false },
  ]
);

watch(
  list,
  () => {
    localStorage.setItem('todos', JSON.stringify(list.value));
  },
  { deep: true }
);

const changeDone = (data) => {
  console.log('data -----> ', data);
  const obj = list.value.find((v) => v.id === data.id);
  obj.done = data.done;
};

const del = (id) => {
  // console.log('id -----> ', id);
  // 1. splice
  // const index = list.value.findIndex((v) => v.id === id);
  // list.value.splice(index, 1);
  // 2. filter
  list.value = list.value.filter((v) => v.id !== id);
};

const add = (name) => {
  console.log('name -----> ', name);
  const obj = {
    id: +new Date(),
    name,
    done: false,
  };
  list.value.unshift(obj);
};

const changeAll = (bl) => {
  list.value.forEach((v) => (v.done = bl));
};

/* 
为什么建议使用 ref
1. reactive ---> 指向的是 proxy盒子数据
arr = reactive([])
arr = arr.filter()

2. ref ----> 指向的是 代理过的盒子，里面有value属性，value就是我们要使用的数据
arr = ref([])
arr.value = arr.value.filter()
*/
</script>

<template>
  <section class="todoapp">
    <TodoHeader @add="add"></TodoHeader>
    <TodoMain
      :list="list"
      @changeDone="changeDone"
      @del="del"
      @changeAll="changeAll"
    ></TodoMain>
    <TodoFooter :list="list"></TodoFooter>
  </section>
</template>

<style></style>
